﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ARS.Control.Attributes;
using ARS.Control.Custom.DataPaging.Attributes;
using ARS.Control.Custom.DataPaging.Widget;
using ARS.Control.Custom.TreeListView.Attributes;
using ARS.Control.Custom.TreeListView.Resource;
using ARS.PublicTool.DataHandle;


namespace ARS.Control.Custom.TreeListView.Widget
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TreeListView runat=server></{0}:TreeListView>")]
    public class TreeListView : Literal
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        private DbSelectTree _DbSelectTree;
        [Bindable(true), Category("Appearance"), Description("sql相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public DbSelectTree AttrDbSelect
        {
            get
            {
                if (_DbSelectTree == null)
                {
                    _DbSelectTree = new DbSelectTree();
                }
                return _DbSelectTree;
            }
            set
            {
                _DbSelectTree = value;
            }
        }

        private HtmlUl _HtmlUl;
        [Bindable(true), Category("Appearance"), Description("html相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public HtmlUl AttrHtmlUl
        {
            get
            {
                if (_HtmlUl == null)
                {
                    _HtmlUl = new HtmlUl();
                }
                return _HtmlUl;
            }
            set
            {
                _HtmlUl = value;
            }
        }

        private Operat _Operat;
        [Bindable(true), Category("Appearance"), Description("和最后一列按钮相关属性"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public Operat AttrOperat
        {
            get
            {
                if (_Operat == null)
                {
                    _Operat = new Operat();
                }
                return _Operat;
            }
        }

        private Attributes.Status _status;
        public Attributes.Status AttrStatus
        {
            get
            {
                if (this._status == null)
                {
                    this._status = new Attributes.Status();
                }
                return this._status;
            }
            set
            {
                _status = value;
            }
        }

        private ARS.Control.Custom.Entity.Model.EntityModel _entity;
        public ARS.Control.Custom.Entity.Model.EntityModel Entity
        {
            get { return _entity; }
            set
            {
                _entity = value;
            }
        }
        public ARS.Control.Common.EntityManage.EntityTableInfo EntityTableInfo
        {
            get { return Entity.GetEntityTableInfo(); }
        }

        protected override void OnPreRender(EventArgs e)
        {


            ARS.Control.Interface.IDialog dialog = ARS.Control.Factory.DialogFactory.CreateDialog();

            this.Page.ClientScript.RegisterStartupScript(typeof(TreeListView), "dp", ARS.PublicTool.WebHelper.WebPage.ScriptHelper.GetScriptStr(string.Format("function DeleteData(id) {{ {0} }}", dialog.TreeListView_DelConfirm(this.Page, typeof(TreeListView)))));
            base.OnPreRender(e);
        }

        private ARS.DataBase.Provider.IDbProvider _dbProvider = ARS.DataBase.Provider.DbProvider.GetInstance();

        private ARS.DataBase.Provider.IDataPagingProvider _dpProvider =
            ARS.DataBase.Provider.DataPagingProvider.GetInstance();
        public override void RenderControl(HtmlTextWriter output)
        {
            if (this.Entity != null)
            {
                List<ARS.Control.Custom.Entity.Fields.Field> fields = null;
                Func<List<ARS.Control.Custom.Entity.Fields.Field>> getLieldList = () =>
                {
                    if (fields == null)
                    {
                        fields = this.EntityTableInfo.FieldList.Where(field => field.IsListShow == true).OrderBy(
                            field => field.RankList).ToList();
                    }
                    return fields;
                };
                if (this.EntityTableInfo.KeyInfo != null)
                {
                    this.AttrDbSelect.TableName = this.EntityTableInfo.TableName;
                    this.AttrDbSelect.KeyField = this.EntityTableInfo.KeyInfo.Key;

                    if (this.AttrDbSelect.OrderField == null)
                    {
                        this.AttrDbSelect.OrderField = this.AttrDbSelect.KeyField + " desc";
                    }
                    if (this.AttrDbSelect.SelectFields == null)
                    {
                        List<ARS.Control.Custom.Entity.Fields.Field> fieldList = getLieldList();
                        this.AttrDbSelect.SelectFields = this.AttrDbSelect.KeyField + "," + string.Join(",", from item in fieldList select item.Db_Field_Name);
                    }
                }
            }
            output.Write("<script type=\"text/javascript\">" + Res_Tree.TreeListView.Replace("{{TableName}}", Encrypt.EncryptString(AttrDbSelect.TableName)).Replace("{{ParentName}}", AttrDbSelect.ParentFieldName).Replace("{{keyField}}",this.AttrDbSelect.KeyField) + "</script>");

            _where = AttrDbSelect.StrWhere;
            _dsAll = (DbSelectAll)AttrDbSelect;

            if (AttrDbSelect.ParentFieldName == null || AttrDbSelect.FieldFirstValue == null)
            {
                this.DataBindList("", output, 0);
            }
            else
            {
                this.DataBindList(string.Format(" and {0}='{1}'", AttrDbSelect.ParentFieldName, AttrDbSelect.FieldFirstValue), output, 0);
            }
        }

        public delegate string UpdateLiLineHtmlDelegate(int index);
        /// <summary>
        /// 更新行的html
        /// </summary>
        public event UpdateLiLineHtmlDelegate UpdateLiLineHtmlEvent = (index) => { return null; };
        
        
        //public delegate string UpdateLiLineHtmlDelegate(int index);
        /// <summary>
        /// 添加行完成后回调
        /// </summary>
        public event UpdateLiLineHtmlDelegate AddLineEvent = (index) => { return null; };


        public delegate string UpdateUlLiHtmlDelegate(int index,DataRow dr);

        /// <summary>
        /// 获取li的html
        /// </summary>
        public event UpdateUlLiHtmlDelegate UpdateUlLiHtmlEvent;//= (dr) => { return GetUlLiHtml(); };
        //public event UpdateLiLineHtmlDelegate AddLineEvent = (index) => { return null; }; 

        public string GetUlLiHtml()
        {
            return "<li id='{0}'>";
        }

        private string _where;
        private DbSelectAll _dsAll;
        private void DataBindList(string where, HtmlTextWriter output,int index)
        {
            string lineHtml = this.UpdateLiLineHtmlEvent(index);
            if (lineHtml == null)
            {
                lineHtml = AttrHtmlUl.LiLineHtml;
            }

            if (this.AttrStatus.MaxLevelNumber != 0 && index == this.AttrStatus.MaxLevelNumber)
            {
                return;
            }
            if (AttrHtmlUl.UlCssNameList == null)
            {
                output.Write(string.Format("<ul id={0}>",this.ID));
                
            }
            else
            {
                output.Write(string.Format("<ul class='{0}' id={1}>", AttrHtmlUl.UlCssNameList[index], this.ID));
            }
            
            _dsAll.StrWhere = this._where + where;
            DataSet ds = _dpProvider.GetDataList(_dsAll);
            DataTable dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                string id = Encrypt.EncryptString(dr[AttrDbSelect.KeyField].ToString());
                if (this.UpdateUlLiHtmlEvent == null)
                {
                    output.Write(this.GetUlLiHtml(), id);
                }
                else
                {
                    output.Write(this.UpdateUlLiHtmlEvent(index, dr), id);
                }

                
                //output.Write(string.Format("<li id='{0}'>",id));

                output.Write(Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().GetTreeLineHtml(lineHtml, dr, AttrDbSelect));
                
                if (AttrOperat.OperatHtml != null)
                {
                    output.Write(string.Format(AttrOperat.OperatHtml, id));
                }
                if (this.AttrStatus.MaxLevelNumber==0 || index < this.AttrStatus.MaxLevelNumber)
                {
                    this.DataBindList(string.Format(" and {0}='{1}'", AttrDbSelect.ParentFieldName, dr[AttrDbSelect.KeyField]), output, index + 1);
                }

                output.Write("</li>");
            }
            output.Write("</ul>");
            output.Write(this.AddLineEvent(index));
        }
        //private string RepeatString(int num, string str)
        //{
        //    //if (num <1)
        //    //{
        //    //    return null;
        //    //}
        //    StringBuilder retStr = new StringBuilder();
        //    for (int i = num; i > 0; i--)
        //    {
        //        retStr.Append(str);
        //    }
        //    return retStr.ToString();
        //} 
    }
}
